package com.vieewer.btdemo.view.wifi.connect;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.lindroid.androidutilskt.extension.ToastUtil;
import com.vieewer.btdemo.bean.*;
import com.vieewer.btdemo.utils.CommunicateToPhoneHelper;
import com.vieewer.btdemo.utils.LogUtil;
import com.vieewer.btdemo.utils.SugonInfoUtils;
import com.vieewer.btdemo.utils.WifiUtils;
import java.io.BufferedReader;
import java.io.FileReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class WifiConnectManager {

    private WifiManager wifiManager;
    private WifiConfiguration config;
    private int wcgID;

    /**
     * 热点名称
     */
    private static final String WIFI_HOTSPOT_SSID = "TEST";
    /**
     * 端口号
     */
    private static final int PORT = 54321;
    private static final int WIFICIPHER_NOPASS = 1;
    private static final int WIFICIPHER_WEP = 2;
    private static final int WIFICIPHER_WPA = 3;

    public static final int DEVICE_CONNECTING = 1;//有设备正在连接热点
    public static final int DEVICE_CONNECTED = 2;//有设备连上热点
    public static final int SEND_MSG_SUCCSEE = 3;//发送消息成功
    public static final int SEND_MSG_ERROR = 4;//发送消息失败
    public static final int GET_MSG = 6;//获取新消息

    /**
     * 连接线程
     */
    //private ConnectThread connectThread;

    /**
     * 监听线程
     */
    private ListenerThread listenerThread;

    private Context mContext;
    private WifiUtils mUtils;

    private boolean mIsStarted = false;


    private WifiConnectManager() {

    }

    private static class Instance {
        public static WifiConnectManager singletonState = new WifiConnectManager();
    }

    public static WifiConnectManager getNewInstance() {
        return Instance.singletonState;
    }

    public void init (Context context) {
        mContext = context;
        mUtils = new WifiUtils(context);

        wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
        listenerThread = new ListenerThread(PORT, handler);

    }

    public void unRegister() {
        if (receiver != null) {
            mContext.unregisterReceiver(receiver);
        }
        handler.removeCallbacksAndMessages(null);

        //if (listenerThread != null) {
            //listenerThread.interrupt();
            //listenerThread.close();
            //listenerThread = null;
        //}

    /*    if (connectThread != null) {
            connectThread.interrupt();
            connectThread = null;
        }*/

    }

    private void initWifi() {
        initBroadcastReceiver();
        if (listenerThread != null && !mIsStarted) {
            Log.i("yjj", "listenerThread start");
            listenerThread.start();
            mIsStarted = true;
        }
    }





    private void connect(WifiConfiguration config) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                wcgID = wifiManager.addNetwork(config);
                boolean success = wifiManager.enableNetwork(wcgID, true);
                if (success) {
                    Log.i("yjj", "connect success");
                    handler1.sendEmptyMessage(0);

                } else {
                    Log.i("yjj", "connect failed");
                    handler1.sendEmptyMessage(1);
                }
            }
        }).start();
    }

    private void initBroadcastReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
//        intentFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
        mContext.registerReceiver(receiver, intentFilter);
    }



    //处理事件逻辑

    public void handleMsg(WifiLinkBean bean) {
        if (bean != null) {
            Log.i("yjj", "receive msg from phone ~~~" + ", type =" + bean.getBtntype());
            if (bean.getBtntype().equals("搜索")) {
                initWifi();
                search();
            } else if (bean.getBtntype().equals("连接wifi")) {
                WifiLinkBean.ScanResultBean scanResult = bean.getScanResult();

                // 判断密码输入情况
                if (TextUtils.isEmpty(bean.getPsd())) {
                    Toast.makeText(mContext, "请输入wifi密码", Toast.LENGTH_SHORT).show();
                    return;
                }

                MyScanResult myScanResult = new MyScanResult();
                myScanResult.ssid = scanResult.getSsid();
                myScanResult.level = scanResult.getLevel();
                myScanResult.capabilities = scanResult.getCapabilities();

                //connectWifi(myScanResult, bean.getPsd());
                dealWithConnect(scanResult.getSsid(), bean.getPsd(), scanResult.getCapabilities());
            }
        }

    }
    private void connectWifi(MyScanResult scanResult, String pwd) {

        wifiManager.disconnect();
        String capabilities = scanResult.capabilities;
        int type = WIFICIPHER_WPA;
        if (!TextUtils.isEmpty(capabilities)) {
            if (capabilities.contains("WPA") || capabilities.contains("wpa")) {
                type = WIFICIPHER_WPA;
            } else if (capabilities.contains("WEP") || capabilities.contains("wep")) {
                type = WIFICIPHER_WEP;
            } else {
                type = WIFICIPHER_NOPASS;
            }
        }
        config = isExsits(scanResult.ssid);
        if (config == null) {
            if (type != WIFICIPHER_NOPASS) {//需要密码

                final int finalType = type;
                config = createWifiInfo(scanResult.ssid, pwd, finalType);
                connect(config);

                return;
            } else {
                config = createWifiInfo(scanResult.ssid, "", type);
                connect(config);
            }
        } else {
            connect(config);
        }


    }

    private void dealWithConnect(final String ssid, final String pwd, final String capabilities) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();

                int type = WIFICIPHER_WPA;
                if (!TextUtils.isEmpty(capabilities)) {
                    if (capabilities.contains("WPA") || capabilities.contains("wpa")) {
                        type = WIFICIPHER_WPA;
                    } else if (capabilities.contains("WEP") || capabilities.contains("wep")) {
                        type = WIFICIPHER_WEP;
                    } else {
                        type = WIFICIPHER_NOPASS;
                    }
                }
                // 检验密码输入是否正确
                boolean pwdSucess = mUtils.connectWifiTest(ssid, pwd, type);
                try {
                    Thread.sleep(4000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (pwdSucess) {
                    handler1.sendEmptyMessage(0);
                } else {
                    handler1.sendEmptyMessage(1);
                }

            }
        }).start();
    }

    private void sendSuccessToPhone() {

        SugonInfoBean data = new SugonInfoBean();
        data.type = "sugonInfo";
        data.bluetoothName = SugonInfoUtils.Companion.getBluetoothName();
        data.connectWifiName = SugonInfoUtils.Companion.getConnectWifiSsid(mContext);
        data.diskValue = SugonInfoUtils.Companion.getDiskValue();
        data.totalValue = SugonInfoUtils.Companion.getDiskTotal();
        String dataStr = JSON.toJSONString(data);
        LogUtil.e("yjj", "sendSuccessToPhone");
        CommunicateToPhoneHelper.Companion.getInstance().write(dataStr);

    }

    private void sendFailedMsgToPhone() {
        WifiConnectFailedBean data = new WifiConnectFailedBean();
        data.type = "wifi_connect_failed";
        LogUtil.e("yjj", "connect wifi failed , send to phone");
        String dataStr = JSON.toJSONString(data);
        CommunicateToPhoneHelper.Companion.getInstance().write(dataStr);
    }


    /**
     * 创建Wifi热点
     */
    private void createWifiHotspot() {
        if (wifiManager.isWifiEnabled()) {
            //如果wifi处于打开状态，则关闭wifi,
            wifiManager.setWifiEnabled(false);
        }
        WifiConfiguration config = new WifiConfiguration();
        config.SSID = WIFI_HOTSPOT_SSID;
        config.preSharedKey = "123456789";
        config.hiddenSSID = true;
        config.allowedAuthAlgorithms
                .set(WifiConfiguration.AuthAlgorithm.OPEN);//开放系统认证
        config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
        config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        config.allowedPairwiseCiphers
                .set(WifiConfiguration.PairwiseCipher.TKIP);
        config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
        config.allowedPairwiseCiphers
                .set(WifiConfiguration.PairwiseCipher.CCMP);
        config.status = WifiConfiguration.Status.ENABLED;
        //通过反射调用设置热点
        try {
            Method method = wifiManager.getClass().getMethod(
                    "setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE);
            boolean enable = (Boolean) method.invoke(wifiManager, config, true);
            if (enable) {
                //textview.setText("热点已开启 SSID:" + WIFI_HOTSPOT_SSID + " password:123456789");
            } else {
                //textview.setText("创建热点失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            //textview.setText("创建热点失败");
        }
    }

    /**
     * 关闭WiFi热点
     */
    public void closeWifiHotspot() {
        try {
            Method method = wifiManager.getClass().getMethod("getWifiApConfiguration");
            method.setAccessible(true);
            WifiConfiguration config = (WifiConfiguration) method.invoke(wifiManager);
            Method method2 = wifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
            method2.invoke(wifiManager, config, false);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //textview.setText("热点已关闭");
        //text_state.setText("wifi已关闭");
    }

    /**
     * 获取连接到热点上的手机ip
     *
     * @return
     */
    private ArrayList<String> getConnectedIP() {
        ArrayList<String> connectedIP = new ArrayList<String>();
        try {
            BufferedReader br = new BufferedReader(new FileReader(
                    "/proc/net/arp"));
            String line;
            while ((line = br.readLine()) != null) {
                String[] splitted = line.split(" +");
                if (splitted != null && splitted.length >= 4) {
                    String ip = splitted[0];
                    connectedIP.add(ip);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connectedIP;
    }

    /**
     * 搜索wifi热点
     */
    private void search() {
        if (!wifiManager.isWifiEnabled()) {
            //开启wifi
            wifiManager.setWifiEnabled(true);
        }
        wifiManager.startScan();
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        /*    switch (msg.what) {
                case DEVICE_CONNECTING:
                    //connectThread = new ConnectThread(listenerThread.getSocket(),handler);
                    //connectThread.start();
                    break;
                case DEVICE_CONNECTED:
                    //textview.setText("设备连接成功");
                    break;
                case SEND_MSG_SUCCSEE:
                    //textview.setText("发送消息成功:" + msg.getData().getString("MSG"));
                    break;
                case SEND_MSG_ERROR:
                    //textview.setText("发送消息失败:" + msg.getData().getString("MSG"));
                    break;
                case GET_MSG:
                    //textview.setText("收到消息:" + msg.getData().getString("MSG"));
                    break;

            }*/


        }
    };


    private Handler handler1= new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 0:
                    ToastUtil.shortToast("WIFI连接成功");
                    //sendSuccessToPhone();
                    break;
                case 1:
                    ToastUtil.shortToast("WIFI连接失败");
                    //sendFailedMsgToPhone();
                    break;
            }
        }
    };




    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
                Log.w("BBB", "SCAN_RESULTS_AVAILABLE_ACTION");
                // wifi已成功扫描到可用wifi。
                List<ScanResult> scanResults = wifiManager.getScanResults();
                //todo 收到手机端搜索信号 把搜索结果发送给手机端
                List<MyScanResult> datas = new ArrayList<>();
                for (int i = 0 ; i < scanResults.size(); i++) {
                    MyScanResult bean = new MyScanResult();
                    bean.capabilities = scanResults.get(i).capabilities;
                    bean.level = scanResults.get(i).level;
                    bean.ssid = scanResults.get(i).SSID;
                    datas.add(bean);
                }
                WifiResultBean data = new WifiResultBean();
                data.wifiResultDatas = datas;
                data.type = "wifiResult";
                String dataStr = JSON.toJSONString(data);
                LogUtil.e("yjj", dataStr);

                //todo 防止ANR
                new Thread(() -> CommunicateToPhoneHelper.Companion.getInstance().write(dataStr)).start();

                unRegister();

            } else if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
                Log.w("BBB", "WifiManager.WIFI_STATE_CHANGED_ACTION");
                int wifiState = intent.getIntExtra(
                        WifiManager.EXTRA_WIFI_STATE, 0);
                switch (wifiState) {
                    case WifiManager.WIFI_STATE_ENABLED:
                        //获取到wifi开启的广播时，开始扫描
                        wifiManager.startScan();
                        break;
                    case WifiManager.WIFI_STATE_DISABLED:
                        //wifi关闭发出的广播
                        break;
                }
            } else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
                Log.w("BBB", "WifiManager.NETWORK_STATE_CHANGED_ACTION");
                NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                if (info.getState().equals(NetworkInfo.State.DISCONNECTED)) {
                    //text_state.setText("连接已断开");
                } else if (info.getState().equals(NetworkInfo.State.CONNECTED)) {
                    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                    final WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                    //text_state.setText("已连接到网络:" + wifiInfo.getSSID());
                    Log.w("AAA","wifiInfo.getSSID():"+wifiInfo.getSSID()+"  WIFI_HOTSPOT_SSID:"+WIFI_HOTSPOT_SSID);
 /*                   if (wifiInfo.getSSID().equals(WIFI_HOTSPOT_SSID)) {
                        //如果当前连接到的wifi是热点,则开启连接线程
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    ArrayList<String> connectedIP = getConnectedIP();
                                    for (String ip : connectedIP) {
                                        if (ip.contains(".")) {
                                            Log.w("AAA", "IP:" + ip);
                                            Socket socket = new Socket(ip, PORT);
                                            connectThread = new ConnectThread(socket, handler);
                                            connectThread.start();
                                        }
                                    }

                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }).start();
                    }*/
                } else {
                    NetworkInfo.DetailedState state = info.getDetailedState();
                    if (state == state.CONNECTING) {
                        ToastUtil.shortToast("连接中...");
                        //text_state.setText("连接中...");
                    } else if (state == state.AUTHENTICATING) {
                        ToastUtil.shortToast("正在验证身份信息...");
                        //text_state.setText("正在验证身份信息...");
                    } else if (state == state.OBTAINING_IPADDR) {
                        ToastUtil.shortToast("正在获取IP地址...");
                        //text_state.setText("正在获取IP地址...");
                    } else if (state == state.FAILED) {
                        ToastUtil.shortToast("连接失败");
                        //text_state.setText("连接失败");
                    }
                }

            }
           /* else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)) {
                    text_state.setText("连接已断开");
                    wifiManager.removeNetwork(wcgID);
                } else {
                    WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
                    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                    text_state.setText("已连接到网络:" + wifiInfo.getSSID());
                }
            }*/
        }
    };



    /**
     * 判断当前wifi是否有保存
     *
     * @param SSID
     * @return
     */
    private WifiConfiguration isExsits(String SSID) {
        List<WifiConfiguration> existingConfigs = wifiManager.getConfiguredNetworks();
        for (WifiConfiguration existingConfig : existingConfigs) {
            if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
                return existingConfig;
            }
        }
        return null;
    }

    public WifiConfiguration createWifiInfo(String SSID, String password,
                                            int type) {
        Log.w("AAA", "SSID = " + SSID + "password " + password + "type ="
                + type);
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + SSID + "\"";
        if (type == WIFICIPHER_NOPASS) {
            config.wepKeys[0] = "\"" + "\"";
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        } else if (type == WIFICIPHER_WEP) {
            config.preSharedKey = "\"" + password + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms
                    .set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedGroupCiphers
                    .set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedGroupCiphers
                    .set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers
                    .set(WifiConfiguration.GroupCipher.WEP40);
            config.allowedGroupCiphers
                    .set(WifiConfiguration.GroupCipher.WEP104);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        } else if (type == WIFICIPHER_WPA) {
            config.preSharedKey = "\"" + password + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms
                    .set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers
                    .set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedKeyManagement
                    .set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedPairwiseCiphers
                    .set(WifiConfiguration.PairwiseCipher.TKIP);
            // config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            config.allowedGroupCiphers
                    .set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedPairwiseCiphers
                    .set(WifiConfiguration.PairwiseCipher.CCMP);
            config.status = WifiConfiguration.Status.ENABLED;
        } else {
            return null;
        }
        return config;
    }

}
